package org.summer.netty;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

@Slf4j
public class NIOTest {
    public static void main(String[] args) {
        new NIOTest().test();
    }

    @Test
    public void test() {
        try {
            ArrayList<SocketChannel> socketChannels = new ArrayList<>();
            ByteBuffer buffer = ByteBuffer.allocate(16);

            final ServerSocketChannel ssc = ServerSocketChannel.open();

            ssc.bind(new InetSocketAddress(8080));

            for (; ; ) {
                log.info("waiting connecting ...");
                SocketChannel sc = ssc.accept();
                log.info("a socket channel connected ...");
                socketChannels.add(sc);

                for (SocketChannel socketChannel : socketChannels) {
                    log.info("before read -> {}", socketChannel);
                    socketChannel.read(buffer);
                    buffer.flip();
                    PacketSplicing.byteBuffPrint(buffer);
                    buffer.clear();
                    log.info("after read -> {}", socketChannel);
                }
            }
        } catch (IOException e) {
            log.error("error -> {}", e);
        }
    }

    @Test
    public void test1() throws IOException {
        SocketChannel sc = SocketChannel.open();
        sc.connect(new InetSocketAddress("127.0.0.1",8080));
        System.in.read();
    }
}
